package com.zq.blog.service.impl;

import com.zq.blog.dao.CommentRepository;
import com.zq.blog.po.Comment;
import com.zq.blog.service.CommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Override
    public List<Comment> listCommentByBlogId(Long blogId) {
        Sort sort = Sort.by("createTime");
        List<Comment> comments = commentRepository.findByBlogIdAndParentCommentNull(blogId, sort);

        return eachComment(comments);
    }

    private List<Comment> eachComment(List<Comment> comments) {
        ArrayList<Comment> commentsView = new ArrayList<>();
        for (Comment comment :
                comments) {
            Comment c = new Comment();
            BeanUtils.copyProperties(comment, c);
            commentsView.add(c);
        }
        combineChildren(commentsView);
        return commentsView;
    }

    private void combineChildren(ArrayList<Comment> commentsView) {
        for (Comment comment :
                commentsView) {
            List<Comment> replys1 = comment.getReplyComments();
            for (Comment reply1 :
                    replys1) {
                recursively(reply1);
            }

            comment.setReplyComments(tempReplys);
            tempReplys = new ArrayList<>();
        }
    }

    private List<Comment> tempReplys = new ArrayList<>();

    private void recursively(Comment comment) {
        tempReplys.add(comment);
        if (comment.getReplyComments().size() > 0) {
            List<Comment> replys = comment.getReplyComments();
            for (Comment reply :
                    replys) {
                tempReplys.add(reply);
                if (reply.getReplyComments().size() > 0) {
                    recursively(reply);
                }
            }
        }
    }

    @Override
    public Comment saveComment(Comment comment) {
        return null;
    }
}
